<template>
    <div class="app-container">
        <!-- 查询条件 -->
        <el-card>
            <el-form ref="configRef" :inline="true" :model="queryParams" label-width="68px">

                <el-form-item label="参数名称" prop="configName">
                    <el-input v-model="queryParams.configName" placeholder="请输入参数名称" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="参数键名" prop="configKey">
                    <el-input v-model="queryParams.configKey" placeholder="请输入参数键名" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="系统内置" prop="configType">
                    <el-select v-model="queryParams.configType" placeholder="系统内置" clearable>
                        <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="创建时间" style="width: 308px">
                    <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!--制作表格-->
        <el-card style="margin-top: 20px;">
            <template #header>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:config:add']" type="primary" plain icon="Plus"
                            @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:config:edit']" type="success" plain icon="Edit"
                            :disabled="single" @click="handleUpdate()">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:config:remove']" type="danger" plain icon="Delete"
                            :disabled="multiple" @click="handleDelete()">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:config:export']" type="warning" plain icon="Download"
                            @click="handleExport">导出</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:config:remove']" type="danger" plain
                            icon="Refresh">刷新缓存</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" :data="pageData.rows" style="width: 100%"
                @selectionChange="handleSelectionChange">
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="参数主键" align="center" prop="configId" />
                <el-table-column label="参数名称" align="center" prop="configName" :show-overflow-tooltip="true" />
                <el-table-column label="参数键名" align="center" prop="configKey" :show-overflow-tooltip="true" />
                <el-table-column label="参数键值" align="center" prop="configValue" :show-overflow-tooltip="true" />
                <el-table-column label="系统内置" align="center" prop="configType">
                    <template #default="scope">
                        <dict-tag :options="sys_yes_no" :value="scope.row.configType" />
                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
                <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                    <template #default="scope">
                        <span>{{parseTime(scope.row.createTime)}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button v-hasPermi="['system:config:edit']" circle type="primary" icon="Edit"
                            @click="handleUpdate(scope.row)" />
                        <el-button v-hasPermi="['system:config:remove']" circle type="danger" icon="Delete"
                            @click="handleDelete(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="pageData.total > 0" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" :total="pageData.total" @pagination="getList" />
        </el-card>

        <!-- 新增修改对话框  -->
        <el-dialog v-model="open" :title="title" width="500" :close-on-click-modal="false">
            <el-form ref="editRef" :model="form" label-width="80px">
                <el-form-item label="参数名称" prop="configName"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-input v-model="form.configName" placeholder="请输入参数名称" />
                </el-form-item>

                <el-form-item label="参数键名" prop="configKey"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-input v-model="form.configKey" placeholder="请输入参数键名" />
                </el-form-item>

                <el-form-item label="参数键值" prop="configValue"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-input v-model="form.configValue" placeholder="请输入参数键值" />
                </el-form-item>

                <el-form-item label="系统内置" prop="configType"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-radio-group v-model="form.configType">
                        <el-radio v-for="dict in sys_yes_no" :key="dict.value"
                            :label="dict.value">{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup name="Config" lang="ts">
    /* eslint-disable camelcase */
    import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from 'vue';
    import { SysConfigQueryReq, FormReq, SysConfigResp } from '@/types/config';
    import { listConfig, getConfig, addConfig, updateConfig, delConfig } from '@/api/system/config';
    import { parseTime } from '@/utils/ruoyi';
    import type { FormInstance } from 'element-plus';

    // 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { sys_yes_no } = proxy!.useDict('sys_yes_no');

    //响应式对象
    const dateRange = ref<any[]>([]);
    const loading = ref<boolean>(false);

    // 默认不启用编辑按钮
    const single = ref<boolean>(true);
    //默认不启用删除按钮
    const multiple = ref<boolean>(true);
    const showSearch = ref<boolean>(true);
    // 表格选中的值
    const mutilSelection = ref<SysConfigResp[]>([]);
    // 表格选中的主键的值
    const ids = ref<number[]>([]);

    // 对话框配置
    const open = ref(false);
    const title = ref('');

    // 表单验证对象
    const editRef = ref<FormInstance>();

    // 分页数据
    const pageData = reactive<{
        total : number,
        rows : SysConfigResp[]
    }>({
        total: 0,
        rows: []
    });

    /**
     * 定义响应式的代理模型
     */
    const data = reactive<{
        form : FormReq;
        queryParams : SysConfigQueryReq;
    }>({
        // 初始化值
        form: {
            configId: undefined,
            configName: '',
            configKey: '',
            configType: '',
            configValue: '',
            remark: ''
        },
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            configName: '',
            configKey: '',
            configType: ''
        }
    });

    // 代理模型转换为响应式模型
    const { queryParams, form } = toRefs(data);


    // 搜索
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    // 重置
    function resetQuery() {
        dateRange.value = [];
        // utils/ruoyi.ts
        proxy?.resetForm('configRef');
        //查询
        handleQuery();
    }

    // 分页查询
    function getList() {
        loading.value = true;

        // 添加日期值
        listConfig(proxy?.addDateRange(queryParams.value, dateRange.value)).then((resp : any) => {
            pageData.total = resp.data.total;
            pageData.rows = resp.data.list;
            loading.value = false;
        });
    }

    // 多选框选中数据
    function handleSelectionChange(selection : SysConfigResp[]) {
        mutilSelection.value = selection;
        ids.value = selection.map(row => row.configId);
        // 判断 修改按钮禁用
        single.value = selection.length !== 1;
        // 判断 删除按钮禁用
        multiple.value = selection.length === 0;
    }

    // 新增
    function handleAdd() {
        reset();
        title.value = '参数设置--新增';
        open.value = true;
    }

    // 修改
    function handleUpdate(row ?: null | SysConfigResp) {
        let primaryKey : number;
        if (row) {
            primaryKey = row.configId;
        } else {
            primaryKey = ids.value[0];
        }
        console.log(primaryKey);
        //还原数据
        reset();

        // 从后台查询值是多少
        getConfig(primaryKey).then((resp : any) => {
            form.value = resp.data;
            title.value = '参数设置--修改';
            open.value = true;
        });
    }

    // 删除 或 禁用
    function handleDelete(row ?: SysConfigResp) {
        let primaryKeys : any;
        if (row) {
            primaryKeys = row.configId;
        } else {
            primaryKeys = ids.value;
        }

        proxy?.$modal
            .confirm('是否确认删除参数编号为"' + primaryKeys + '"的数据项？')
            .then(function () {
                return delConfig(primaryKeys);
            })
            .then(() => {
                getList();
                proxy!.$modal.msgSuccess('删除成功');
            })
            .catch((e : any) => {
                console.log(e);
            });
    }

    // 导出
    function handleExport() {
        let queryData : any = {};
        // 根据勾选行下载
        if (ids.value && ids.value.length > 0) {
            queryData.ids = ids.value.join();
        } else {
            queryData = {
                ...queryParams.value
            };
        }

        proxy?.download(
            'admin/config/export',
            queryData,
            `config_${new Date().getTime()}.xlsx`
        );
    }

    // 新增或修改 提交按钮
    async function submitForm() {
        // vue2判断前端表单数据有效性
        // proxy?.$refs['editRef'].validate((valid: boolean) => {
        //     if (valid) {
        //         alert('submit!');
        //     } else {
        //         console.log('error submit!!');
        //         return false;
        //     }
        // });

        // vue3写法
        if (!editRef.value) {
            return;
        }
        await editRef.value.validate((valid : boolean, fields : any) => {
            if (valid) {
                // 调用修改请求
                if (form.value.configId) {
                    updateConfig(form.value).then(() => {
                        proxy?.$modal.msgSuccess('修改成功');
                        open.value = false;
                        getList();
                    });
                } else {
                    //调用新增请求
                    addConfig(form.value).then(() => {
                        proxy?.$modal.msgSuccess('新增成功');
                        open.value = false;
                        getList();
                    });
                }
            } else {
                console.log('error submit!', fields);
            }
        });
    }

    // 新增或修改 对话框取消按钮
    function cancel() {
        open.value = false;
    }

    /** 表单重置 */
    function reset() {
        form.value = {
            configId: undefined,
            configName: '',
            configKey: '',
            configValue: '',
            configType: 'Y',
            remark: '',
        };
        // 重置表单样式
        proxy?.resetForm('editRef');
    }

    // 初始化列表
    getList();
</script>
